/**
 * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.zzmcc.weixin;

import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.jfinal.MsgController;
import com.jfinal.weixin.sdk.msg.in.*;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InQrCodeEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.*;
import com.zzmcc.sys.model.Userinfo;
import com.zzmcc.jms.model.News;
import util.ChristStringUtil;
import util.ChristDateUtils;
import util.ChristStringUtil;

import java.util.List;

import static com.zzmcc.jms.common.ModelConfigWms.TABLE_News;

/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由，
 * 并设置好weixin开发者中心的 URL 与 token ，使 URL 指向该
 * DemoController 继承自父类 WeixinController 的 index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
public class WeixinMsgController extends MsgController {

	private static final String helpStr = "\t公众号持续更新中，欢迎大家对我们的工作提出宝贵意见和建议 ^_^";
	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
	 * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();

		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));

		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;

	}

	/**
	 * 实现父类抽方法，处理文本消息
	 * 本例子中根据消息中的不同文本内容分别做出了不同的响应，同时也是为了测试 jfinal weixin sdk的基本功能：
	 *     本方法仅测试了 OutTextMsg、OutNewsMsg、OutMusicMsg 三种类型的OutMsg，
	 *     其它类型的消息会在随后的方法中进行测试
	 */
	protected void processInTextMsg(InTextMsg inTextMsg) {
		String msgContent = inTextMsg.getContent().trim();
		// 帮助提示
		if ("帮助".equalsIgnoreCase(msgContent)) {
			OutTextMsg outMsg = new OutTextMsg(inTextMsg);
			outMsg.setContent(helpStr);
			render(outMsg);
		}

		// 其它文本消息直接返回原值 + 帮助提示
		else {
			OutTextMsg outMsg = new OutTextMsg(inTextMsg);
			outMsg.setContent("\t感谢您提供的宝贵意见！");
			render(outMsg);
		}
	}
	/**
	 * 实现父类抽方法，处理自定义菜单事件
	 */
	protected void processInMenuEvent(InMenuEvent inMenuEvent) {


		if ("2001".equalsIgnoreCase(inMenuEvent.getEventKey())) {
			OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
			StringBuffer sb = new StringBuffer();
			String username = inMenuEvent.getFromUserName();
			try {
				Userinfo userinfo = Userinfo.dao.findFirst("select * from sys_userinfo where username=?",username);
				String inuse = userinfo.get("inuse").toString();

				if (inuse.equalsIgnoreCase("1")){
					sb.append("您已登记信息，待管理员核实！");
				}else  if (inuse.equalsIgnoreCase("0")){
					sb.append("更新工程进度：<a href=\"http://121.42.148.189/zztt/project\">点击进入</a>");
				}
			}catch (Exception e){
				sb.append("信息核实：<a href=\"http://121.42.148.189/zztt/member/add/"+username+"\">点击申请</a>");
			}
			outMsg.setContent(sb.toString());
			render(outMsg);

		}else if ("2002".equalsIgnoreCase(inMenuEvent.getEventKey())){

			OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
			StringBuffer sb = new StringBuffer();
			String username = inMenuEvent.getFromUserName();
			try {
				Userinfo userinfo = Userinfo.dao.findFirst("select * from sys_userinfo where username=?",username);
				String inuse = userinfo.get("inuse").toString();
				if (inuse.equalsIgnoreCase("1")){
					sb.append("您已登记信息，待管理员核实！");
				}else  if (inuse.equalsIgnoreCase("0")){
					sb.append("工程领料明细：<a href=\"http://121.42.148.189/zztt/stock\">点击进入查看</a>");
				}
			}catch (Exception e){
				sb.append("信息核实：<a href=\"http://121.42.148.189/zztt/member/add/"+username+"\">点击申请</a>");
			}
			outMsg.setContent(sb.toString());
			render(outMsg);

		}else{
			  	String newType = inMenuEvent.getEventKey();
				//新闻 type=1001, 通知1002,3001>建设维护=3002>运营管理3003>地市创新3004>综合管理
				List<News> newsList = News.dao.find("select * from " + TABLE_News +
						" where type= ? order by createDate desc limit 0,10 ", newType);
				OutNewsMsg outMsg = new OutNewsMsg(inMenuEvent);
				//图片链接，支持JPG、PNG格式，较好的效果为大图360*200，小图200*200
				for(News x:newsList){
					outMsg.addNews(ChristStringUtil.castString(x.get("name")),
							ChristStringUtil.castString(x.get("content")),
							ChristStringUtil.castString(x.get("picUrl")),
							ChristStringUtil.castString(x.get("url")));
				}
				render(outMsg);

		}

	}
	/**
	 * 实现父类抽方法，处理图片消息
	 */
	protected void processInImageMsg(InImageMsg inImageMsg) {
		OutImageMsg outMsg = new OutImageMsg(inImageMsg);
		// 将刚发过来的图片再发回去
		outMsg.setMediaId(inImageMsg.getMediaId());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理语音消息
	 */
	protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
		OutVoiceMsg outMsg = new OutVoiceMsg(inVoiceMsg);
		// 将刚发过来的语音再发回去
		outMsg.setMediaId(inVoiceMsg.getMediaId());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理视频消息
	 */
	protected void processInVideoMsg(InVideoMsg inVideoMsg) {

		OutTextMsg outMsg = new OutTextMsg(inVideoMsg);
		outMsg.setContent("\t视频消息已成功接收，该视频的 mediaId 为: " + inVideoMsg.getMediaId());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理地址位置消息
	 */
	protected void processInLocationMsg(InLocationMsg inLocationMsg) {
		OutTextMsg outMsg = new OutTextMsg(inLocationMsg);
		outMsg.setContent("已收到地理位置消息:" +
				"\nlocation_X = " + inLocationMsg.getLocation_X() +
				"\nlocation_Y = " + inLocationMsg.getLocation_Y() +
				"\nscale = " + inLocationMsg.getScale() +
				"\nlabel = " + inLocationMsg.getLabel());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理链接消息
	 * 特别注意：测试时需要发送我的收藏中的曾经收藏过的图文消息，直接发送链接地址会当做文本消息来发送
	 */
	protected void processInLinkMsg(InLinkMsg inLinkMsg) {
		OutNewsMsg outMsg = new OutNewsMsg(inLinkMsg);
		outMsg.addNews("链接消息已成功接收", "链接使用图文消息的方式发回给你，还可以使用文本方式发回。点击图文消息可跳转到链接地址页面，是不是很好玩 :)" , "http://mmbiz.qpic.cn/mmbiz/zz3Q6WSrzq1ibBkhSA1BibMuMxLuHIvUfiaGsK7CC4kIzeh178IYSHbYQ5eg9tVxgEcbegAu22Qhwgl5IhZFWWXUw/0", inLinkMsg.getUrl());
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理关注/取消关注消息
	 */
	protected void processInFollowEvent(InFollowEvent inFollowEvent) {
		OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
		outMsg.setContent("感谢关注 !\n " + helpStr);
		// 如果为取消关注事件，将无法接收到传回的信息
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理扫描带参数二维码事件
	 */
	protected void processInQrCodeEvent(InQrCodeEvent inQrCodeEvent) {
		OutTextMsg outMsg = new OutTextMsg(inQrCodeEvent);
		outMsg.setContent("processInQrCodeEvent() 方法测试成功");
		render(outMsg);
	}

	/**
	 * 实现父类抽方法，处理上报地理位置事件
	 */
	protected void processInLocationEvent(InLocationEvent inLocationEvent) {
		OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
		outMsg.setContent("processInLocationEvent() 方法测试成功");
		render(outMsg);
	}



	/**
	 * 实现父类抽方法，处理接收语音识别结果
	 */
	protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults) {
		OutTextMsg outMsg = new OutTextMsg(inSpeechRecognitionResults);
		outMsg.setContent("processInSpeechRecognitionResults() 方法测试成功");
		render(outMsg);
	}

}






